//
//  RecordSupplyController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/18.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import FSCalendar

class RecordSupplyController: UIViewController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            _tableView.isScrollEnabled = false
            
//            _tableView.register(ProjectCell.self, forCellReuseIdentifier: "\(ProjectCell.self)")
            _tableView.register(UINib.init(nibName: "ProjectNormalCell", bundle: nil), forCellReuseIdentifier: "ProjectNormalCell")
            
            return _tableView
        }
    }
    
    fileprivate var calendar: FSCalendar = {
        let calendar = FSCalendar()

        calendar.locale = Locale(identifier: "zh-CN")
        calendar.appearance.todayColor = UIColor.clear//去掉今日色
        calendar.appearance.titleTodayColor = UIColor.black//去掉今日色导致标题色消失，因此需要再次加上
        calendar.appearance.headerTitleColor = colorWith255RGB(74, g: 144, b: 226)//月份标题颜色
        calendar.appearance.weekdayTextColor = colorWith255RGB(66, g: 66, b: 66) //星期标题颜色
        calendar.placeholderType = .none    //占位用来显示上月尾部和下月头部的信息
        calendar.scrollEnabled = false
        calendar.backgroundColor = UIColor.white

        return calendar
    }()
    fileprivate lazy var dateFormatter1: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy/MM/dd"
        return formatter
    }()
    
    var projectModel: ProjectModel?
    
    var displayDate = Date() //当前显示的日期
    
    var recordSupplyLists: [RecordSupply]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "补工"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "申请记录", style: .done, target: self, action: #selector(doRightAction))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)

        self.setupViews()
        self.getData()
        
        calendar.calendarHeaderView.isUserInteractionEnabled = true
        calendar.calendarHeaderView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doTapCalendarHeaderViewAction)))
    
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func setupViews() {
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(100 + 64 + 25)
        }
        
        self.calendar.delegate = self
        self.calendar.dataSource = self
        self.view.addSubview(self.calendar)
        self.calendar.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.tableView.snp.bottom).offset(15)
        }
        
        let bottomPanel = UIView()
        self.view.addSubview(bottomPanel)
        bottomPanel.backgroundColor = UIColor.white
        bottomPanel.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.calendar.snp.bottom).offset(10)
            make.height.equalTo(30)
            make.bottom.equalTo(self.view).offset(-50)
        }
        
        let blueRoundView = UIView()
        blueRoundView.backgroundColor = UIColor.mg_blue
        blueRoundView.layer.cornerRadius = 8
        bottomPanel.addSubview(blueRoundView)
        blueRoundView.snp.makeConstraints { (make) in
            make.left.equalTo(bottomPanel).offset(30)
            make.centerY.equalTo(bottomPanel)
            make.height.width.equalTo(16)
        }
        
        let blueExplainLabel = UILabel()
        blueExplainLabel.text = "正常"
        blueExplainLabel.font = wwFont_Regular(14)
        blueExplainLabel.textColor = colorWith255RGB(102, g: 102, b: 102)
        bottomPanel.addSubview(blueExplainLabel)
        blueExplainLabel.snp.makeConstraints { (make) in
            make.left.equalTo(blueRoundView.snp.right).offset(8)
            make.centerY.equalTo(bottomPanel)
        }
        
        let pinkRoundView = UIView()
        pinkRoundView.backgroundColor = UIColor.mg_pink
        pinkRoundView.layer.cornerRadius = 8
        bottomPanel.addSubview(pinkRoundView)
        pinkRoundView.snp.makeConstraints { (make) in
            make.left.equalTo(blueExplainLabel.snp.right).offset(15)
            make.centerY.equalTo(bottomPanel)
            make.height.width.equalTo(blueRoundView)
        }
        
        let pinkExplainLabel = UILabel()
        pinkExplainLabel.text = "工时不足"
        pinkExplainLabel.font = wwFont_Regular(14)
        pinkExplainLabel.textColor = colorWith255RGB(102, g: 102, b: 102)
        bottomPanel.addSubview(pinkExplainLabel)
        pinkExplainLabel.snp.makeConstraints { (make) in
            make.left.equalTo(pinkRoundView.snp.right).offset(8)
            make.centerY.equalTo(bottomPanel)
        }
    }
    
    func doRightAction() {
        
        let vc = RecordSupplyListController()
        vc.currentProject = self.projectModel
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func doTapCalendarHeaderViewAction() {
        let dateAlertController = DateAlertController.init { [unowned self](date) in
            self.calendar.currentPage = date
        }
        dateAlertController.date = self.calendar.currentPage
        self.present(dateAlertController, animated: true, completion: nil)
    }
    
    func getData() {
        let firstDay = displayDate.startOfMonth()
        let lastDay = displayDate.endOfMonth()
        
        let firstDayString = dateTimeToString(date: firstDay)
        let lastDayString = dateTimeToString(date: lastDay)
        
        let demandBaseMigrantWorkerID = self.projectModel!.demandBaseMigrantWorkerID
        if demandBaseMigrantWorkerID != nil {
            RecordSupply.getRecordStatisticInMonth(workerId: demandBaseMigrantWorkerID!, startTime: firstDayString, lastTime: lastDayString) {(response) in
                if response.success {
                    self.recordSupplyLists = response.value
                    self.calendar.reloadData()
                }
                else {
                    WWError("获取签到记录错误")
                }
            }
        }
    }
 
    deinit {

    }
}

extension RecordSupplyController :UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100 + 25
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(ProjectNormalCell.self)", for: indexPath) as! ProjectNormalCell
        cell.accessoryType = .disclosureIndicator
        cell.bind(self.projectModel!)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let vc = ProjectListViewController()
        vc.confirmSelection = {[unowned self](projectModel) in
            self.projectModel = projectModel
            tableView.reloadData()
            
            self.getData()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension RecordSupplyController :FSCalendarDelegateAppearance, FSCalendarDelegate,FSCalendarDataSource {
    //MARK:FSCalendar
    //点击某个cell后调用
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        guard date <= Date() else {//未来还没到，咋签到
           // WWError("只能补签今天之前的考勤！")
            return
        }
        
        //let vc = RecordSupplyDisplayController()
        let vc = MemorandumListViewController(nibName: "MemorandumListViewController", bundle: nil)
        guard let model = self.projectModel else {
            WWError("请先选择项目")
            return
        }
        
        vc.selectDate = date
        vc.projectModel = model
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //月历的月份改变触发
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        self.displayDate = calendar.currentPage
        self.getData()
    }
    
    //对应date的cell的背景色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? {
        guard date <= Date() else {
            
            return UIColor.lightGray
        }
        
        if let lists = self.recordSupplyLists {
            for item in lists {
                if date == item.signedDate {
                    switch item.exceptionState {
                    case .unSigned:
                        return nil
                    case .signed:
                        return colorWith255RGB(73, g: 169, b: 238)
                    case .other:
                        return colorWith255RGB(244, g: 110, b: 101)
                    }
                }
            }
        }
        return nil
    }
    //修改指定日期的颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
        guard date <= Date() else {
            return UIColor.white
        }
        
        if let lists = self.recordSupplyLists {
            for item in lists {
                if date == item.signedDate {
                    switch item.exceptionState {
                    case .unSigned:
                        return nil
                    case .signed,.other:
                        return UIColor.white
                        
                    }
                }
            }
        }
        return colorWith255RGB(66, g: 66, b: 66)
    }
    
    
    //去掉选中色，titleSelectionColorFor指cell中文字色，fillSelectionColorFor指cell背景色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleSelectionColorFor date: Date) -> UIColor? {
        
        if let lists = self.recordSupplyLists {
            for item in lists {
                if date == item.signedDate {
                    switch item.exceptionState {
                    case .unSigned:
                        return nil
                    case .signed,.other:
                        return UIColor.white
                    }
                }
            }
        }
        return UIColor.white
    }
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? {
        if let lists = self.recordSupplyLists {
            for item in lists {
                if date == item.signedDate {
                    switch item.exceptionState {
                    case .unSigned:
                        return nil
                    case .signed:
                        return colorWith255RGB(73, g: 169, b: 238)
                    case .other:
                        return colorWith255RGB(244, g: 110, b: 101)
                    }
                }
            }
        }
        return UIColor.gray
    }
}
